package com.lanxin.xxform.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lanxin.xxform.aspects.exceptions.ParamException;
import com.lanxin.xxform.services.AnswerService;
import com.lanxin.xxform.tools.JsonResult;

@RestController
@RequestMapping("/answer")
public class AnswerController {

    @Autowired
    private AnswerService answerService;

    /**
     * 保存答卷
     * @param name
     * @param phone
     * @param pid
     * @return
     */
    @PostMapping("submit.do")
    public JsonResult createAnswer(
        @RequestParam(required = true) String name,
        @RequestParam(required = true) String phone,
        @RequestParam(required = true) String datas,
        @RequestParam(required = true) long pid
    ) {
        long aid = answerService.createAnswer(pid, name, phone);
        if (! datas.startsWith("[")) {
            throw new ParamException("问卷提交个内容格式错误");
        }
        JSONArray items = JSONArray.parseArray(datas);
        int c = 0;
        for (int i = 0; i < items.size(); i++) {
            JSONObject o = items.getJSONObject(i);
            answerService.saveAnswer(aid, o.getIntValue("id"), o.getString("subtitle"), o.getString("answer").trim());
            c++;
        }
        return new JsonResult(c);
    }

    /**
     * 统计答卷数量
     * @param pid
     * @param status
     * @param keyword
     * @param uid
     * @return
     */
    @PostMapping("getCount.do")
    public JsonResult getCount(
        @RequestParam(defaultValue = "0") long pid,
        @RequestParam(defaultValue = "0") int status,
        @RequestParam(defaultValue = "") String keyword,
        long uid
    ) {
        return new JsonResult(answerService.getCount(uid, pid, status, keyword));
    }

    /**
     * 获取答卷列表
     * @param offset
     * @param limit
     * @param pid
     * @param status
     * @param keyword
     * @param uid
     * @return
     */
    @PostMapping("getList.do")
    public JsonResult getList(
        @RequestParam(defaultValue = "0") int offset,
        @RequestParam(defaultValue = "10") int limit,
        @RequestParam(defaultValue = "0") long pid,
        @RequestParam(defaultValue = "0") int status,
        @RequestParam(defaultValue = "") String keyword,
        long uid
    ) {
        return new JsonResult(answerService.getList(offset, limit, uid, pid, status, keyword));
    }
    
}
